<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户姓名" prop="nickName">
        <el-input v-model="queryParams.nickName" placeholder="用户姓名" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="上岗证" prop="postsNumber">
        <el-input v-model="queryParams.postsNumber" placeholder="请输入用户名称" clearable class="input-w-180"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList">
      <el-table-column type="selection" width="50" align="center"/>
      <el-table-column label="头像" align="center" prop="name" width="50">
        <template slot-scope="scope">
          <viewer v-if="scope.row.avatar != undefined && scope.row.avatar != null && scope.row.avatar != ''">
            <el-avatar size="large" :src="scope.row.avatar"></el-avatar>
          </viewer>
          <el-avatar v-else size="large" src=""></el-avatar>
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center" prop="nickName" :show-overflow-tooltip="true" width="100"/>
      <el-table-column label="上岗证" align="center" prop="postsNumber" :show-overflow-tooltip="true" width="150"/>
<!--      <el-table-column label="初复训" align="center">-->
<!--        <template slot-scope="scope">-->
<!--          <el-tag v-if="scope.row.userInfo?.reservedOne == 1">复训</el-tag>-->
<!--          <el-tag v-else type="success">初训</el-tag>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="部门" align="center" prop="dept.deptName" :show-overflow-tooltip="true"/>
      <el-table-column label="社区" align="center" prop="userInfo.community"/>
      <el-table-column label="执业类别" align="center" prop="userInfo.practiceType"/>
      <el-table-column label="执业范围" align="center" prop="userInfo.practiceRange"/>
      <el-table-column label="所在科室/岗位" align="center" prop="userInfo.posts"/>
      <el-table-column label="联系方式" align="center" prop="phonenumber"/>
      <el-table-column label="参加初训年份" align="center" prop="userInfo.initialTraining"/>
      <el-table-column label="出生年月" align="center" prop="identity">
        <template slot-scope="scope" v-if="scope.row.userId !== 1">
          {{ parseTime(scope.row.birthday, '{y}-{m}-{d}') }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="培训记录" width="100" type="expand">
        <template slot-scope="scope">
          <!-- 学生报名记录 -->
          <el-table :data="scope.row.studyRecords" :row-class-name="studyRecordsClassName"
                    border max-height="250" size="mini">
            <el-table-column label="培训班" align="center" prop="trainingClass.name"/>
            <el-table-column label="教师" align="center" prop="trainingClass.teacher"/>
            <el-table-column label="颁证时间" align="center" prop="cert.issuanceDate"/>
            <el-table-column label="证书编号" align="center" prop="cert.certNo"/>
            <el-table-column label="报名时间" align="center" prop="certTime">
              <template slot-scope="scope1">
                {{ parseTime(scope1.row.createTime, '{y}-{m}-{d}') }}
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="status">
              <template slot-scope="scope1">
                <dict-tag :options="dict.type.pv_study_record_status" :value="scope1.row.status"/>
              </template>
            </el-table-column>
            <el-table-column label="考试分数" align="center" prop="exStudyReload.score"/>
            <el-table-column label="产妇总分" align="center" prop="puerperaTotalPoints"/>
            <el-table-column label="新生儿总分" align="center" prop="childrenTotalPoints"/>
            <el-table-column label="评分表总分" align="center">
              <template slot-scope="scope1">
                {{ scope1.row.puerperaTotalPoints + scope1.row.childrenTotalPoints }}
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="130" class-name="small-padding fixed-width">
              <template slot-scope="scope1">
                <el-button size="mini" type="text" icon="el-icon-edit"
                           @click="openScore(scope1.row,scope.row.nickName)">评分表
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>

    <!-- 查看评分表对话框 -->
    <el-drawer :wrapperClosable="false" :visible.sync="score.open" size="80%" append-to-body destroy-on-close>
      <div slot="title">
        {{ score.title }} <br><span style="font-size: 10px;">按ESC可退出</span>
      </div>
      <div style="padding: 1rem">
        教师：
        <el-tag type="success" effect="plain">{{ score.teacher.nickName }}</el-tag>
        <el-tabs v-model="score.activeName">
          <el-tab-pane label="产妇" name="puerpera" :disabled="!checkPermi(['pv:stu_record:edit:pregnant'])"></el-tab-pane>
          <el-tab-pane label="新生儿" name="children" :disabled="!checkPermi(['pv:stu_record:edit:child'])"></el-tab-pane>
        </el-tabs>
        <div>
          <center>
            <el-table :data="score.model" style="width: 100%" border :span-method="objectSpanMethod" size="mini"
                      :header-cell-style="{ textAlign: 'center' }">
              <el-table-column>
                <template slot="header" slot-scope="scope">
                <span
                  style="font-size: 20px;font-family: 仿宋;">产褥期保健操作评分表（{{ score.activeName === 'puerpera' ? '产妇' : '新生儿' }}）</span>
                  <el-button style="float: right;" size="mini" icon="el-icon-circle-check" type="success"
                             @click="recordUpdate" v-hasPermi="['pv:stu_record:edit']" round>提交
                  </el-button>
                </template>
                <el-table-column prop="project" align="center" label="项目"></el-table-column>
                <el-table-column prop="step" align="center" label="步骤"></el-table-column>
                <el-table-column prop="content" align="center" label="具体内容" width="500"></el-table-column>
                <el-table-column prop="value" align="center" label="分值"></el-table-column>
                <el-table-column label="得分" width="105">
                  <template slot-scope="scope">
                    <el-input-number v-if="isNotNull(score.scores[scope.$index])" controls-position="right"
                                     @input="$forceUpdate()"
                                     style="width: 84px" :min="0" :max="scope.row.value"
                                     v-model="score.scores[scope.$index]"/>
                  </template>
                </el-table-column>
              </el-table-column>
            </el-table>
            <el-input style="width: 1027px;margin-top: 5px" type="textarea" :rows="6" placeholder="备注"
                      v-model="score.comments"/>

          </center>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {listUser} from "@/api/system/userStudent";
import {readJson} from "@/api/file";
import {updateStu_record} from "@/api/pv/stu_record";
import {arrSum, copyArr} from '@/utils/zzDouUtils/arrayUtil'
import {isNotEmpty, parseObj, toJsonStr} from "@/utils/zzDouUtils/ObjUtil";
import {checkPermi} from "@/utils/permission";

export default {
  name: "User",
  dicts: ['sys_normal_disable', 'sys_user_sex', 'pv_study_record_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined
      },
      score: {
        open: false,
        title: '',
        obj: {},
        puerperaScore: null,
        childrenScore: null,
        puerperaComment: null,
        childrenComment: null,
        scores: null,//展示的表格的分数
        comments: null,//展示的的备注
        activeName: 'puerpera',
        model: [],
        puerperaModel: [],
        childrenModel: [],
        teacher: JSON.parse(window.localStorage.getItem('user'))
      },
      project_merageArr: [],  //第一列进行合并操作时存放的数组变量
      project_meragePos: 0,  //上面的数组的下标值
      step_merageArr: [],  //第二列进行合并操作时存放的数组变量
      step_meragePos: 0, //上面的数组的下标值
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
    'score.activeName': function (n, o) {
      if (n === 'puerpera') {
        this.score.scores = this.score.puerperaScore;
        this.score.childrenComment = this.score.comments;
        this.score.comments = this.score.puerperaComment;
        this.score.model = copyArr(this.score.puerperaModel);
      } else {
        this.score.scores = this.score.childrenScore;
        this.score.puerperaComment = this.score.comments;
        this.score.comments = this.score.childrenComment;
        this.score.model = copyArr(this.score.childrenModel);
      }
      this.merage();
    },
    'score.scores': {
      handler(n, o) {
        this.score.model[this.score.model.length - 1].step = arrSum(this.score.scores);
      },
      deep: true,//深度监听
    },
  },
  created() {
    this.getList();
    this.getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg;
    });
    //读取json文件
    readJson('children').then(response => {
      this.score.childrenModel = response.data
    });
    readJson('puerpera').then(response => {
      this.score.puerperaModel = response.data
    });
  },
  methods: {
    isNotEmpty,
    checkPermi,
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        avatar: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        identity: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        postIds: [],
        roleIds: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    /** 培训记录颜色 */
    studyRecordsClassName({row, rowIndex}) {
      if (rowIndex === 0) {
        return 'warning-row';
      }
    },
    //--------------------------------------------------------
    /** 打开评分表 */
    openScore(row, name) {
      this.score.title = row.trainingClass.name + ' - ' + name;
      this.score.obj = row;
      this.score.comments = row.puerperaComment;
      this.score.puerperaScore = parseObj(row.puerperaScore);
      this.score.childrenScore = parseObj(row.childrenScore);
      this.score.puerperaComment = row.puerperaComment;
      this.score.childrenComment = row.childrenComment;
      if (checkPermi(['pv:stu_record:edit:pregnant'])){
        this.score.activeName = 'puerpera';
        this.score.scores = this.score.puerperaScore;
        this.score.model = copyArr(this.score.puerperaModel);
      }else if(checkPermi(['pv:stu_record:edit:child'])){
        this.score.activeName = 'children';
        this.score.scores = this.score.childrenScore;
        this.score.model = copyArr(this.score.childrenModel);
      }
      this.merage();
      this.score.open = true;
    },
    /** 修改 */
    recordUpdate() {
      var body = {
        id: this.score.obj.id,
        puerperaScore: toJsonStr(this.score.puerperaScore),
        childrenScore: toJsonStr(this.score.childrenScore),
        puerperaComment: this.score.puerperaComment,
        childrenComment: this.score.childrenComment,
      }
      updateStu_record(body).then(response => {
        this.$message({
          message: '提交成功',
          type: 'success',
          offset: '300'
        });
        //this.resetScore();
        this.getList();
      });
    },
    resetScore() {
      this.score.title = '';
      this.score.obj = {};
      this.score.scores = [];
      this.score.activeName = 'puerpera';
      this.score.model = [];
    },
    /**--------------------------------------*/
    merageInit() { // 在下文的时候会用到，对数据进行初始化是很有必要的
      this.project_merageArr = [];
      this.project_meragePos = 0;
      this.step_merageArr = [];
      this.step_meragePos = 0;
    },
    // 合并多列专用
    merage() {
      this.merageInit(); // 前文的初始化数据函数
      for (let i = 0; i < this.score.model.length; i++) {
        if (i === 0) {
          // 第一行必须存在
          this.project_merageArr.push(1);
          this.project_meragePos = 0;
          this.step_merageArr.push(1);
          this.step_meragePos = 0;
        } else {
          // 判断当前元素与上一个元素是否相同,eg：this.paragraph_meragePos 是 this.typeNameArr序号
          // 第一列
          if (this.score.model[i].project === this.score.model[i - 1].project) {
            this.project_merageArr[this.project_meragePos] += 1;
            this.project_merageArr.push(0);
          } else {
            this.project_merageArr.push(1);
            this.project_meragePos = i;
          }
          // 第二列
          if (this.score.model[i].step === this.score.model[i - 1].step && this.score.model[i].project === this.score.model[i - 1].project) {
            this.step_merageArr[this.step_meragePos] += 1;
            this.step_merageArr.push(0);
          } else {
            this.step_merageArr.push(1);
            this.step_meragePos = i;
          }
        }
      }
    },
    //合并列的方法
    objectSpanMethod({row, column, rowIndex, columnIndex}) {
      //合并最后一行 合计
      if (rowIndex === this.score.model.length - 1) {
        return [1, 4];
      }
      if (columnIndex === 0) {
        // 第一列的合并方法
        const row1 = this.project_merageArr[rowIndex];
        const col1 = row1 > 0 ? 1 : 0; // 如果被合并了row = 0; 则他这个列需要取消
        return {rowspan: row1, colspan: col1};
      } else if (columnIndex === 1) {
        // 第二列的合并方法
        const row2 = this.step_merageArr[rowIndex];
        const col2 = row2 > 0 ? 1 : 0; // 如果被合并了row = 0; 则他这个列需要取消
        return {rowspan: row2, colspan: col2};
      }
    }
  }
};
</script>
<style>
.el-table .warning-row {
  background: oldlace;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-table .cell {
  white-space: pre-line;
}
</style>
